#!/usr/bin/env python
# _*_coding:utf-8_*_
import os

from django.conf import settings
from django.db import models

from django.utils import timezone

from common.models import CommonAuto
from shop.models import ShopInfo


class PublicInfo(object):
    """公众号信息"""
    BUSINESS_INFO = [u'微信门店', u'微信扫商品', u'微信支付', u'微信卡券', u'微信摇一摇']
    FUNC_INFO = [u'消息管理权限', u'用户管理权限', u'帐号服务权限', u'网页服务权限', u'微信小店权限', u'微信多客服权限',
                 u'群发与通知权限', u'微信卡券权限', u'微信扫一扫权限', u'微信连WIFI权限', u'素材管理权限',
                 u'微信摇周边权限', u'微信门店权限', u'微信支付权限', u'自定义菜单权限']
    FUNC_INFO_MAP = {'1': '消息管理权限', '2': '用户管理权限', '3': '帐号服务权限', '4': '网页服务权限', '5': '微信小店权限', '6': '微信多客服权限',
                     '7': '群发与通知权限', '8': '微信卡券权限', '9': '微信扫一扫权限', '10': '微信连WIFI权限', '11': '素材管理权限', '12': '微信摇周边权限',
                     '13': '微信门店权限', '14': '微信支付权限', '15': '自定义菜单权限', '16': '获取认证状态及信息', '17': '帐号管理权限(小程序)',
                     '18': '开发管理与数据分析权限(小程序)', '19': '客服消息管理权限(小程序)', '20': '微信登录权限(小程序)', '21': '数据分析权限(小程序)',
                     '22': '城市服务接口权限', '23': '广告管理权限', '24': '开放平台帐号管理权限', '25': '开放平台帐号管理权限(小程序)', '26': '微信电子发票权限'}


class ComponentTicket(CommonAuto):
    """component_verify_ticket，用于获取第三方平台接口调用凭据"""

    ticket = models.CharField(u'ticket', max_length=128, default='', blank=True)
    timestamp = models.CharField(u'时间戳', max_length=20, default='', blank=True)

    def __unicode__(self):
        return self.ticket

    class Meta:
        db_table = 'component'
        verbose_name = '开放平台信息'


class ComponentAccessToken(CommonAuto):
    """
    开放平台component access token，第三方平台通过自己的接口调用凭据（component_access_token）来获取用于授权流程准备的预授权码（pre_auth_code）
    """

    token = models.CharField(u'令牌', max_length=256, default='')
    expires = models.IntegerField(u'过期时间', default=7200)

    def __unicode__(self):
        return self.token

    class Meta:
        db_table = 'component_access_token'
        verbose_name = '开放平台令牌'


class PreAuthCode(CommonAuto):
    """开放平台预授权码"""
    code = models.CharField(u'令牌', max_length=256, default='')
    expires = models.IntegerField(u'过期时间', default=1200)

    def __unicode__(self):
        return self.code

    class Meta:
        db_table = 'pre_auth_code'
        verbose_name = '开放平台预授权码'


class WxPublicMapShop(CommonAuto):
    """微信公众号和店铺间映射"""
    shop = models.OneToOneField(ShopInfo, verbose_name=u'店铺', related_name='public_shop', on_delete=models.CASCADE)
    app_id = models.CharField(u'公众号APP ID', max_length=64, default='', blank=True)
    xcx_id = models.CharField(u'小程序APP ID', max_length=64, default='', blank=True)
    mch_id = models.CharField(u'支付商户号', max_length=64, default='', blank=True)
    third_id = models.CharField(u'绑定的第三方平台ID', max_length=64, default='', blank=True)
    auto_red_pkg = models.BooleanField(u'是否可以发放自动红包', default=False)
    T_PLUS_ONE, T_PLUS_TREE, T_PLUS_SEVEN = 0, 1, 2
    T_GROUP = ((T_PLUS_ONE, u'T+1'), (T_PLUS_TREE, U'T+3'), (T_PLUS_SEVEN, u'T+7'))
    settlement_modes = models.IntegerField(u"结算方式", default=T_PLUS_ONE, choices=T_GROUP)

    def __unicode__(self):
        return self.shop_id

    class Meta:
        db_table = 'public_map_shop'
        verbose_name = '公众号店铺映射'


class WxPublicInfo(CommonAuto):
    """公众号信息"""
    app_id = models.CharField(u'公众号APP ID', max_length=64, default='', blank=True)
    nick_name = models.CharField(u'昵称', max_length=64, default='', blank=True)
    head_img = models.CharField(u'头像', max_length=128, default='', blank=True)
    WX_PUBLISH, WX_XCX = 1, 2
    WX_TYPE = ((WX_PUBLISH, u'公众号'), (WX_XCX, u'小程序'))
    wx_type = models.IntegerField(u'类型', choices=WX_TYPE, default=WX_PUBLISH, blank=True)
    SERVICE_TYPE_INFO_PUBLISH, SERVICE_TYPE_INFO_UPDATE, SERVICE_TYPE_INFO_SERVICE = 0, 1, 2
    SERVICE_TYPE = ((SERVICE_TYPE_INFO_PUBLISH, u'订阅号'), (SERVICE_TYPE_INFO_UPDATE, u'历史老帐号升级后的订阅号'),
                    (SERVICE_TYPE_INFO_SERVICE, u'服务号'))
    service_type_info = models.SmallIntegerField(u'公众号类型', choices=SERVICE_TYPE, default=SERVICE_TYPE_INFO_SERVICE)
    verify_type_info = models.SmallIntegerField(u'认证类型', default=-1)
    user_name = models.CharField(u'公众号原始ID', max_length=32, default='')
    alias = models.CharField(u'微信号', max_length=32, default='')
    business_info = models.CharField(u'开通功能', max_length=16, default='')
    qrcode_url = models.CharField(u'二维码图片地址', max_length=256, default='', blank=True)
    func_info = models.CharField(u'授权权限集', max_length=32, default='')

    def __unicode__(self):
        return self.app_id

    def get_business_info(self):
        business_list = self.business_info.split(',')
        for i, value in enumerate(business_list):
            business_list[i] = PublicInfo.BUSINESS_INFO[i]
        return business_list

    def get_func_info(self):
        func_info_list = self.func_info.split(',')
        for i, value in enumerate(func_info_list):
            if value in PublicInfo.FUNC_INFO_MAP:
                func_info_list[i] = PublicInfo.FUNC_INFO_MAP[value]
        # for i, value in enumerate(func_info_list):
        #     func_info_list[i] = PublicInfo.FUNC_INFO[i]
        return func_info_list

    class Meta:
        db_table = 'public_info'
        verbose_name = '公众号信息'


class WxPublicAccess(CommonAuto):
    """公众号token"""
    app_id = models.CharField(u'公众号APP ID', max_length=64, default='', unique=True, blank=True)
    access_token = models.CharField(u'令牌', max_length=256, default='')
    expires = models.IntegerField(u'过期时间', default=7200)
    refresh_token = models.CharField(u'刷新令牌', max_length=256, default='')
    ticket = models.CharField(u'票据', max_length=1024, default='')
    expires_ticket = models.IntegerField(u'票据过期时间', default=7200)

    def __unicode__(self):
        return self.app_id

    class Meta:
        db_table = 'public_access'
        verbose_name = '公众号令牌'


class WxPayInfo(CommonAuto):
    """微信公众号支付所需信息"""
    app_id = models.CharField(u'公众号APP ID', max_length=64, default='', blank=True)
    mch_id = models.CharField(u'支付商户号', max_length=64, default='', blank=True)
    key = models.CharField(u'商户支付密钥', max_length=64, default='', blank=True)
    apiclient_cert = models.TextField(u'cert证书', default='', blank=True)
    apiclient_key = models.TextField(u'key证书', default='', blank=True)
    op_user = models.CharField(u'操作员编号', max_length=32, default='', blank=True)

    def __unicode__(self):
        return self.app_id

    def save(self, *args, **kwargs):
        path = os.path.join(settings.BASE_DIR, settings.MEDIA_ROOT, 'cacert')
        cert_file = open('%s/%s.cert.pem' % (path, self.app_id), 'w')
        cert_file.write(str(self.apiclient_cert))
        cert_file.close()
        key_file = open('%s/%s.key.pem' % (path, self.app_id), 'w')
        key_file.write(str(self.apiclient_key))
        key_file.close()
        return super(WxPayInfo, self).save(*args, **kwargs)

    def get_cert_file_path(self):
        return os.path.join(settings.BASE_DIR, settings.MEDIA_ROOT, 'cacert/%s.cert.pem' % self.app_id)

    def get_key_file_path(self):
        return os.path.join(settings.BASE_DIR, settings.MEDIA_ROOT, 'cacert/%s.key.pem' % self.app_id)

    def get_op_user(self):
        return self.op_user if self.op_user else self.mch_id

    class Meta:
        db_table = 'public_pay_info'
        verbose_name = '公众号支付信息'